<template>
  <view>
    <view class="goods-list">
      <block v-if="goodList.length === 0">
        <view>没有商品可显示</view>
      </block>
      <view v-for="(item, index) in goodList" :key="index" @click="navToDetailPage(item)">
        <my-goods :item="item" :selectedIndex="selectedIndex" :hoverIndex="hoverIndex" :index="index" @select="selectItem"></my-goods>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { onLoad, onReachBottom } from '@dcloudio/uni-app';

// 跳转到商品详情页面
function navToDetailPage(item){
  uni.navigateTo({
    url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
  });
}

// 商品列表数据
const goodList = ref([]);

// 选中状态
const hoverIndex = ref(null); 
const selectedIndex = ref(null);

// 选中某一项
const selectItem = (index) => {
  selectedIndex.value = index;
};

// 响应式对象
const queryObj = reactive({
  query: '',
  cid: '',
  pageNum: 1, // 确保使用一致的属性名
  pageSize: 10
});

// 获取商品数据
async function getGoodsList() {
  const res = await uni.$http.get('/api/public/v1/goods/search', queryObj);
  if (res.data.meta.status === 200) {
    goodList.value = [...goodList.value, ...res.data.message.goods]; // 追加新数据
  }
}

// onLoad 获取参数
onLoad((option) => {
  queryObj.query = option.query || '';
  queryObj.cid = option.cid || '';
});

// 组件挂载时获取数据
onMounted(() => {
  getGoodsList();
});

// 触底加载更多数据
onReachBottom(() => {
  queryObj.pageNum++; // 确保使用一致的属性名
  getGoodsList();
});
</script>

<style lang="scss">
/* 商品列表 */
.goods-list {
  padding: 15px;
  background-color: #f8f8f8;
}
</style>